package com.hospital.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hospital.common.R;
import com.hospital.dto.PatientDto;
import com.hospital.pojo.Patient;
import com.hospital.pojo.Picture;
import com.hospital.service.PatientService;
import com.hospital.service.PictureService;
import com.hospital.utils.GlobalUserUtil;
import javafx.scene.chart.PieChart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author:晓风残月Lx
 * @Date: 2022/11/19 11:02
 */
@Controller
@Slf4j
@RequestMapping("/hospital")
public class PatientController {
    @Resource
    private PatientService patientService;

    @Resource
    private PictureService pictureService;


    @ResponseBody
    @RequestMapping("/patients/list")
    public R toPatientsList(@RequestParam("pageNo")Integer pageNo,
                        @RequestParam("pageSize")Integer pageSize,
                        @RequestParam(value = "name",required = false)String name) {
        Page<Patient> patientPage = new Page<>(pageNo, pageSize);
        Page<Patient> patientList = null;
        Page<Patient> list = patientService.getList(patientPage);
        if (name == null || name.equals("")){
            if (GlobalUserUtil.getDoctorPerms().equals("admin"))//拥有admin权限全部查询
            {
                patientList = patientService.getList(patientPage);
            }
            if (GlobalUserUtil.getDoctorPerms().equals("user"))//拥有用户权限只查询自己的
            {
                patientList = patientService.getListByCreateId(patientPage,GlobalUserUtil.getDoctorId());
            }
        }else{
            if (GlobalUserUtil.getDoctorPerms().equals("admin"))//拥有admin权限全部查询{
            {
                patientList= patientService.getListBySearchName(patientPage,name);
            }
            if (GlobalUserUtil.getDoctorPerms().equals("user"))//拥有用户权限只查询自己的
            {
                patientList= patientService.getListBySearchNameAndCreateId(patientPage,name,GlobalUserUtil.getDoctorId());
            }

        }
        if (patientList == null){
            return R.error("数据库除了问题，请稍后重试！");
        }
        return R.success(patientList);
    }

    @RequestMapping("/add-patient")
    public String addPatientPage() {
        return "add-patient";
    }

    @RequestMapping("/patients")
    public String showPatientPage() {
        return "patients";
    }

    @RequestMapping("/patient-profile")
    public String showPatientProfilePage() {
        return "patient-profile";
    }

    @RequestMapping("/update-patient")
    public String updatePatient(){
        return "update-patient";
    }

    @ResponseBody
    @PostMapping("/addPatient")
    public R addPatient(@RequestBody String req) {
        String name = JSONObject.parseObject(req).getString("name");
        Integer sex = JSONObject.parseObject(req).getInteger("sex");
        String phone = JSONObject.parseObject(req).getString("phone");
        Integer age = JSONObject.parseObject(req).getInteger("age");
        String profile = JSONObject.parseObject(req).getString("profile");
        String time = JSONObject.parseObject(req).getString("startTime");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(time.replaceAll("T", " ") + ":00", df);
        String images = JSONObject.parseObject(req).getString("images");
        String[] image = images.split("&");
        Patient patient = new Patient();
        patient.setName(name);
        patient.setAge(age);
        patient.setPhone(phone);
        patient.setProfile(profile);
        patient.setSex(sex);
        patient.setStartTime(startTime);
        patient.setCreateBy(GlobalUserUtil.getDoctorId());//添加创建人
        Long pId = patientService.insertPatient(patient);
        if (pId > 0) {
            boolean b = pictureService.saveBatchPic(pId,image);
            if (b) {
                return R.success(patient.getName(),"添加患者信息成功！");
            }
            return R.error("添加患者信息失败！");
        }
        return R.error("添加患者基本信息失败！");
    }


    @ResponseBody
    @PostMapping("/updatePatient")
    public R updatePatient(@RequestBody String req) {
        Long id = JSONObject.parseObject(req).getLong("id");
        String name = JSONObject.parseObject(req).getString("name");
        Integer sex = JSONObject.parseObject(req).getInteger("sex");
        String phone = JSONObject.parseObject(req).getString("phone");
        Integer age = JSONObject.parseObject(req).getInteger("age");
        String profile = JSONObject.parseObject(req).getString("profile");
        String time = JSONObject.parseObject(req).getString("startTime");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(time.replaceAll("T", " ") + ":00", df);
        String images = JSONObject.parseObject(req).getString("images");
        String deleteImages = JSONObject.parseObject(req).getString("delete_images");
        String[] image = images.split("&");
        Patient patient = new Patient();
        patient.setPId(id);
        patient.setName(name);
        patient.setAge(age);
        patient.setPhone(phone);
        patient.setProfile(profile);
        patient.setSex(sex);
        patient.setStartTime(startTime);
        if (!deleteImages.equals("")){
            pictureService.deletePictureByPId(patient.getPId(),deleteImages.split(","));
        }
        int flag = patientService.updatePatient(patient);
        if (flag > 0) {
            boolean b =false;
            if (!images.equals("")) {
                b = pictureService.saveBatchPic(patient.getPId(), image);
                if (b) {
                    return R.success(patient.getName(),"修改患者信息成功！");
                }
                else {
                    return R.error("修改患者信息失败！");
                }
            }
            return R.success(patient.getName(),"修改患者信息成功！");
        }
        return R.error("修改患者基本信息失败！");
    }

    @ResponseBody
    @DeleteMapping("/patient/delete")
    public R delete(@RequestParam("id") Integer id){
        if (patientService.deleteById(id)){
            return R.success("删除成功！");
        }
        return R.success("删除失败，请稍后重试！");
    }
    @ResponseBody
    @RequestMapping("/patient-detail")
    public R patientInf(@RequestParam("pId") Integer pId) {
        Patient patient = patientService.getPatient(pId);
        PatientDto patientDto = new PatientDto();
        patientDto.setPatient(patient);
        List<Picture> list = pictureService.getPicturePathList(pId);
        patientDto.setImages(list);
        return R.success(patientDto);
    }

    @ResponseBody
    @RequestMapping("/patient/getOne/{pid}")
    public R getOne(@PathVariable("pid") Integer pId){
        Patient patient = patientService.getOneByPId(pId);
        List<Picture> picturePathList = pictureService.getPicturePathList(pId);
        PatientDto patientDto = new PatientDto();
        patientDto.setImages(picturePathList);
        patientDto.setPatient(patient);
        return R.success(patientDto);
    }
}
